/**
 * ChartUtils.java
 */
package com.pluginsacceptor.plugin.chart;

import org.apache.log4j.Logger;

import com.pluginsacceptor.plugin.chart.model.ChartData;
import com.pluginsacceptor.plugin.chart.model.ChartState;
import com.pluginsacceptor.plugin.chart.model.CurrentChartState;
import com.pluginsacceptor.utils.CommunicationUtils;

/**
 * The utils class
 */
public class ChartUtils {

    /** Logger */
    private static final Logger LOG = Logger.getLogger(ChartUtils.class);

    /**
     * Fill chart data if need
     * @param cellString the source cell string
     * @param currentChartState the current chart state
     * @return <code>true</code> if data has been changed
     */
    public static boolean changeChartData(
        final String cellString,
        final CurrentChartState currentChartState
    ) {
        boolean isChanged = false;
        final int col = CommunicationUtils.getColNumFromCellString(cellString);
        final int row = CommunicationUtils.getRowNumFromCellString(cellString);

        final String value = CommunicationUtils.getValueFromCellString(cellString);
        final ChartState chartState = currentChartState.getChartState();
        if (!CommunicationUtils.isEmptyCell(value)) {
            final ChartData chartData = currentChartState.getBarChartData();
            final boolean isUpdate = (chartState == ChartState.WAIT_UPDATE_DATA);
//            LOG.debug("is update " + isUpdate);
            if (chartData.isTitle(col)) {
                chartData.changeTileItem(value, row, isUpdate);
            } else {
                try {
                    final Double dataItem = Double.parseDouble(value);
                    chartData.changeDataItem(dataItem, row, col, isUpdate);
                    isChanged = true;
                } catch (final Exception e) {
                    LOG.warn("invalid data value '" + value + "'");
                    chartData.changeDataItem(new Double(0), row, col, isUpdate);
                }
            }
            LOG.debug("chartData " + chartData);
        }
        return isChanged;
    }

}
